<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属圈子" prop="circleId">
        <el-select
          v-model="queryParams.circleId"
          placeholder="请选择圈子"
          filterable
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="circle in circleOptions"
            :key="circle.id"
            :label="circle.name"
            :value="circle.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="作者用户" prop="authorUserId">
        <el-select
          v-model="queryParams.authorUserId"
          placeholder="请选择作者用户"
          filterable
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="user in userOptions"
            :key="user.id"
            :label="user.name"
            :value="user.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="帖子标题" prop="postTitle">
        <el-input
          v-model="queryParams.postTitle"
          placeholder="请输入帖子标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="点赞数量 >=" prop="likeCount" class="like-count">
        <el-input
          v-model="queryParams.likeCount"
          placeholder="请输入数字"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评论数量 >=" prop="commentCount" class="comment-count">
        <el-input
          v-model="queryParams.commentCount"
          placeholder="请输入数字"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收藏数量 >=" prop="favoriteCount" class="favorite-count">
        <el-input
          v-model="queryParams.favoriteCount"
          placeholder="请输入数字"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="AI审核状态" prop="aiAuditStatus" class="ai-audit-status">
        <el-select v-model="queryParams.aiAuditStatus" placeholder="请选择AI审核状态" clearable>
          <el-option
            v-for="dict in ai_audit_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['post:post:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['post:post:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属圈子" align="center" prop="circleId">
        <template #default="scope">
          {{ getCircleNameById(scope.row.circleId) }}
        </template>
      </el-table-column>
      <el-table-column label="作者用户" align="center" prop="authorUserId">
        <template #default="scope">
          {{ getUserNameById(scope.row.authorUserId) }}
        </template>
      </el-table-column>
      <el-table-column label="帖子标题" align="center" prop="postTitle" />
      <el-table-column label="帖子图片" align="center" prop="postImages" width="100">
        <template #default="scope">
          <post-images-preview 
            :images="scope.row.postImages" 
            :width="50" 
            :height="50"
          />
        </template>
      </el-table-column>
      <el-table-column label="点赞" align="center" prop="likeCount" width="80" />
      <el-table-column label="评论" align="center" prop="commentCount" width="80" />
      <el-table-column label="收藏" align="center" prop="favoriteCount" width="80" />
      <el-table-column label="AI审核状态" align="center" prop="aiAuditStatus">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.aiAuditStatus == 1">通过</el-tag>
          <el-tag type="danger" v-else-if="scope.row.aiAuditStatus == 2">拒绝</el-tag>
          <el-tag type="info" v-else>待审核</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="详情" align="center" width="100">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleViewDetail(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="AI审核时间" align="center" prop="aiAuditTime" width="150">
        <template #default="scope">
          <span>{{ parseTime(scope.row.aiAuditTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['post:post:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 帖子详情对话框 -->
    <el-dialog title="帖子详情" v-model="detailOpen" width="800px" append-to-body>
      <div class="detail-content">
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">帖子标题：</span>
              <span class="value">{{ detailData.postTitle || '无标题' }}</span>
            </div>
            <div class="info-item">
              <span class="label">所属圈子：</span>
              <span class="value">{{ getCircleNameById(detailData.circleId) }}</span>
            </div>
            <div class="info-item">
              <span class="label">作者：</span>
              <span class="value">{{ getUserNameById(detailData.authorUserId) }}</span>
            </div>
            <div class="info-item">
              <span class="label">创建时间：</span>
              <span class="value">{{ parseTime(detailData.createdTime) }}</span>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h4>帖子内容</h4>
          <div class="content-box">
            {{ detailData.postContent || '无内容' }}
          </div>
        </div>

        <div class="detail-section" v-if="detailData.aiAuditStatus == 2">
          <h4>审核拒绝原因</h4>
          <div class="content-box reject-reason">
            {{ detailData.aiAuditReason || '无拒绝原因' }}
          </div>
        </div>

        <div class="detail-section">
          <h4>统计信息</h4>
          <div class="stats-grid">
            <div class="stat-item">
              <span class="stat-label">点赞：</span>
              <span class="stat-value">{{ detailData.likeCount || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">评论：</span>
              <span class="stat-value">{{ detailData.commentCount || 0 }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">收藏：</span>
              <span class="stat-value">{{ detailData.favoriteCount || 0 }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Post">
import { listPost, getPost, delPost } from "@/api/post/post";
import { listCircle } from "@/api/circle/circle";
import { listUser } from "@/api/system/user";
import PostImagesPreview from "@/components/PostImagesPreview/index.vue";

const { proxy } = getCurrentInstance();
const { ai_audit_status } = proxy.useDict('ai_audit_status');

const postList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const circleOptions = ref([]); // 添加圈子选项变量
const userOptions = ref([]); // 添加用户选项变量

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    circleId: null,
    authorUserId: null,
    postTitle: null,
    likeCount: null,
    commentCount: null,
    favoriteCount: null,
    aiAuditStatus: null,
  }
});

const { queryParams } = toRefs(data);

// 详情对话框相关
const detailOpen = ref(false);
const detailData = ref({});

/** 查询帖子管理列表 */
function getList() {
  loading.value = true;
  listPost(queryParams.value).then(response => {
    postList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除帖子管理编号为"' + _ids + '"的数据项？').then(function() {
    return delPost(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('post/post/export', {
    ...queryParams.value
  }, `post_${new Date().getTime()}.xlsx`)
}

/** 查看详情按钮操作 */
function handleViewDetail(row) {
  detailData.value = row;
  detailOpen.value = true;
}

// 获取圈子列表
function getCircleList() {
  listCircle().then(response => {
    if (response.code === 200 && response.rows) {
      circleOptions.value = response.rows.map(item => ({
        id: item.id,
        name: item.circleName || `圈子${item.id}`
      }));
    } else {
      circleOptions.value = [];
      proxy.$modal.msgError("获取圈子列表失败");
    }
  }).catch(() => {
    circleOptions.value = [];
    proxy.$modal.msgError("获取圈子列表失败");
  });
}

// 获取用户列表
function getUserList() {
  listUser().then(response => {
    if (response.code === 200 && response.rows) {
      userOptions.value = response.rows.map(item => ({
        id: item.userId,
        name: item.nickName || item.userName || `用户${item.userId}`
      }));
    } else {
      userOptions.value = [];
      proxy.$modal.msgError("获取用户列表失败");
    }
  }).catch(() => {
    userOptions.value = [];
    proxy.$modal.msgError("获取用户列表失败");
  });
}

// 添加获取圈子名称的方法
function getCircleNameById(id) {
  if (!id) return '';
  const circle = circleOptions.value.find(item => item.id == id);
  return circle ? circle.name : `圈子${id}`;
}

// 添加获取用户昵称的方法
function getUserNameById(id) {
  if (!id) return '';
  const user = userOptions.value.find(item => item.id == id);
  return user ? user.name : `用户${id}`;
}

getCircleList();
getUserList();
getList();
</script>

<style scoped>
.circle-id :deep(.el-form-item__label) {
  white-space: nowrap;
  width: auto !important;
  min-width: 100px;
}

/* 详情对话框样式 */
.detail-content {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.info-item .label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
  flex-shrink: 0;
}

.info-item .value {
  color: #303133;
  word-break: break-all;
}

.content-box {
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 16px;
  color: #606266;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 200px;
  overflow-y: auto;
}

.reject-reason {
  background: #fef0f0;
  border-color: #f56c6c;
  color: #f56c6c;
}

.stats-grid {
  display: flex;
  gap: 24px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-label {
  font-weight: 500;
  color: #606266;
}

.stat-value {
  color: #409eff;
  font-weight: 600;
  font-size: 16px;
}
.like-count :deep(.el-form-item__label) {
  white-space: nowrap;
  width: auto !important;
  min-width: 100px;
}
.comment-count :deep(.el-form-item__label) {
  white-space: nowrap;
  width: auto !important;
  min-width: 100px;
}
.favorite-count :deep(.el-form-item__label) {
  white-space: nowrap;
  width: auto !important;
  min-width: 100px;
}
.ai-audit-status :deep(.el-select) {
  width: 180px; 
}
.ai-audit-status :deep(.el-form-item__label) {
  white-space: nowrap;
  width: auto !important;
  min-width: 100px;
}
</style>